//
//  IMChatRecordController.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/8/12.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMChatRecordController.h"
#import "MicroDef.h"
#import "UIUtil.h"
#import "QBImagePickerController.h"
#import "ChatToolMoreView.h"
//#import "CHMessageManager.h"
#import "ChildHoodMessage.h"
//#import "CHSThemeManager.h"
#import "UIImageView+WebCache.h"
#import "IMFileManagerController.h"
#import "ChildHoodService.h"
#import "ISTThemeLabel.h"
#import "CContactMgr.h"
#import "CGroupMgr.h"
#import "CFolderMgr.h"
#import "CContactModel.h"
#import "CGroupModel.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "GroupMemberDetailVC.h"
#import "GroupDetailVC.h"
#import "MJRefresh.h"
#import "ChildHoodService.h"
#import "CFileModel.h"
#import "IMFileDownLoadController.h"
#import "CXmppRequestMgr.h"
#import "MyInformationVC.h"
#import "JKAlertDialog.h"
#import "CHSAudioPlayer.h"
#import "UIImage+ImageWithColor.h"
#import "CCHatRecordCell.h"
#import "IMSearchDisplayController.h"
#import "SettingTextCell.h"
#import "IMSearchChatRecordController.h"
#import "UIBarButtonItem+category.h"
#import "IMFowardController.h"
#import "WZNavigationController.h"
#import "WZSearchMessageResultController.h"
#import "ShowMapViewController.h"
@interface IMChatRecordController ()<IMChatRecordControllerDataSource, IMChatRecordControllerDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
    NSInteger num2 ;
    NSInteger num1;
    NSInteger count;
    NSInteger Page;
    CMessageModel *first;
    CMessageModel *last;
    UILabel *lable;
    UIButton *left;
    UIButton *right;
    UISearchBar *_searchBar;
    UISearchDisplayController *_searchDisplayController;

}

@property(nonatomic,retain)CHBubbleMessageCell *messagesCell;

@property (nonatomic, strong) CContactModel *currentUser;
@property (nonatomic, strong) CMessageModel *minMessage;
@property (nonatomic, strong) CMessageModel *maxMessage;
@property (nonatomic, strong) CMessageMgr *messageMgr;
@property (nonatomic, strong) CContactMgr *conMgr;
@property (nonatomic, strong) NSMutableArray *searchArray;

@end

@implementation IMChatRecordController

@synthesize delegate = _delegate;
@synthesize dataSource = _dataSource;
@synthesize messages = _messages;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"REMOVEREDPOT_NOTICE" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"chsaudioPlayerPlayVoice" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mutiViewDownLoadVoiceStatus" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"removeRedPoint" object:nil];
    self.delegate = nil;
    self.dataSource = nil;
    
}



- (NSMutableArray *)searchArray
{
    if (_searchArray == nil) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}
- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark - Initialization
- (void)setup
{
    //bug 8509 fixed by lixu
    CGRect tableFrame = CGRectMake(0.0f, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64 - 44);
    _tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
    _tableView.frame = tableFrame;
    _tableView.backgroundColor = [UIColor clearColor];
//    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.decelerationRate = 0.7;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    __block IMChatRecordController *weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf btnClick:left];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    //增加上拉加载更多
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [weakSelf btnClick:right];
    }];
    [footer setTitle:@"加载更多..." forState:MJRefreshStateRefreshing];
    self.tableView.footer = footer;

}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_searchDisplayController.active) {
        [_searchDisplayController setActive:NO];
    }
    
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.currentUser = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    self.conMgr = [[CContactMgr alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeRedpot:) name:@"REMOVEREDPOT_NOTICE" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeRedPoint:) name:@"removeRedPoint" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePlayVoice:) name:@"chsaudioPlayerPlayVoice" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMutiViewDownLoadVoice:) name:@"mutiViewDownLoadVoiceStatus" object:nil];
    [self setBackgroundColor:[UIColor whiteColor]];
    
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
   self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"icon-delete" title:nil target:self sel:@selector(deleRecrod) titleFont:Font10 titleColor:WhiteColor];
   [self.navigationItem setNewTitleCenter:@"聊天记录"];
    
    //初始化消息数组
    self.messages = [[NSMutableArray alloc] initWithCapacity:1];
    
    //绑定Delegate
    self.delegate = self;
    self.dataSource = self;
    
    self.messageMgr = [[CMessageMgr alloc]init];
    
    if (self.group) {
        
        count = [self.messageMgr loadAllcount:self.group.GroupId];
    } else {
        count = [self.messageMgr loadAllcountWithFriendId:self.member.UserID mineId:self.currentUser.UserID];
    }
    
    [self setup];
    [self createpage];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _searchBar.backgroundImage = [UIImage strechingWithImageName:@"BG-search"];
    //test 研发中心搜素
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    // 添加 searchbar 到 headerview
//    _tableView.tableHeaderView = _searchBar;
    [self.view addSubview:_searchBar];
    
    _searchDisplayController = [[IMSearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchDisplayController.searchResultsDelegate = self;
    _searchDisplayController.delegate = self;
    _searchDisplayController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _searchDisplayController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
    _searchDisplayController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;

    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self loadMessage];
   
    
}
-(void)removeRedPoint:(NSNotification *)notice
{
    __block NSIndexPath *redIndexPath = nil;
    __block NSString *messageId = notice.object;
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.messageId isEqualToString:messageId]) {
            obj.isPlayed = MessageSoundPlayed;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    
    if (redIndexPath == nil) {
        return;
    }
    [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    
}

- (void)removeRedpot:(NSNotification *)notice
{
    
    __block NSIndexPath *redIndexPath = nil;
    __block ChildHoodMessage *childMessage = notice.object;
    CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
    //给服务器发送已听消息
    if (model.SoundPlayStatus != MessageSoundPlayed) {
        NSString *messageID = [NSString string];
        NSRange range = [childMessage.messageId rangeOfString:@"-"];
        if (range.location != NSNotFound) {
            messageID = [childMessage.messageId substringToIndex:range.location];
        }
        else
        {
            messageID = childMessage.messageId;
        }
        [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:messageID messageType:@"sound"];

    model.SoundPlayStatus = childMessage.isPlayed;
    [self.messageMgr updateMessage:model];
    
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        
        if (obj.messageDBID == childMessage.messageDBID) {
            obj.isPlayed = childMessage.isPlayed;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    
    if (redIndexPath == nil) {
        return;
    }
    
    [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];

    }
}

- (void)handlePlayVoice:(NSNotification *)notice
{
    __block NSIndexPath *redIndexPath = nil;
    __block ChildHoodMessage *childMessage = notice.object;
    
    CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
  
    model.SoundPlayStatus = childMessage.isPlayed;
    [self.messageMgr updateMessage:model];
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        
       
        if (obj.messageDBID == childMessage.messageDBID) {
            obj.isPlayed = childMessage.isPlayed;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    if (redIndexPath == nil) {
        return;
    }
    [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];

}

- (void)handleMutiViewDownLoadVoice:(NSNotification *)notice
{
    __block NSIndexPath *redIndexPath = nil;
    __block ChildHoodMessage *childMessage = notice.object;
    
    CMessageModel *model = [self.messageMgr loadMessageByMessageId:childMessage.messageId];
    model.MessageSendedStatus = childMessage.messageStatus;
    [self.messageMgr updateMessage:model];
    
    [self.messages enumerateObjectsUsingBlock:^(ChildHoodMessage *obj, NSUInteger idx, BOOL *stop) {
        
        if (obj.messageDBID == childMessage.messageDBID) {
            obj.messageStatus = childMessage.messageStatus;
            redIndexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            *stop = YES;
        }
    }];
    
    if (redIndexPath == nil) {
        return;
    }
    [self.tableView reloadRowsAtIndexPaths:@[redIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    
}


//  bug 6349 yh
- (void)createpage{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, HARDWARE_SCREEN_HEIGHT - 64.0f - 50.0f, HARDWARE_SCREEN_WIDTH, 50.0f)];
    view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"toolbarBKIcon"]];
    
    
    left = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 0, (HARDWARE_SCREEN_WIDTH - 20)/3.0f, 50)];
    left.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [left setImage:[UIImage imageNamed:@"icon-pageUp"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    if (num1 <= 1) {
        left.enabled = NO;
    } else {
        left.enabled = YES;
    }
    left.tag = 100;
    [view addSubview:left];
    
    lable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(left.frame),0,(HARDWARE_SCREEN_WIDTH - 20)/3.0f, 50.0f)];
    num1 = count/10;
    num2 = count%10;
     // bug 8532 fixed by lixu
    if (num2 && num1 == 0) {
        num1++;
    }
    Page = num1;
    
    lable.text=[NSString stringWithFormat:@"%zd/%zd",num1,num1];
    lable.textAlignment=UITextAlignmentCenter;
    [view addSubview:lable];

    
    right = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lable.frame),0, (HARDWARE_SCREEN_WIDTH - 20)/3.0f, 50)];
    right.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    right.enabled = NO;
    [right setImage:[UIImage imageNamed:@"icon-pageDown"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    right.tag=101;
    [view addSubview:right];
//    UIButton *delright = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-50, 0, 50, 50)];
//    [delright setBackgroundImage:[UIImage imageNamed:@"icon-delete.png"] forState:UIControlStateNormal];
//    [delright addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//    delright.tag = 102;
//    [view addSubview:delright];
    
    //bug  8509 fixed by lixu
//    [self.view addSubview:view];
}
- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case 100:
        {
            if (Page <= 1) {
                [_tableView.header endRefreshing];
                return;
            }
            if (Page <= 2) {
                left.enabled = NO;
                right.enabled = YES;
            } else {
                
                left.enabled = YES;
                right.enabled = YES;
            }
            
            Page=Page-1;
            [self doneLoadMoreMessage:100];
            [_tableView.header endRefreshing];
            lable.text=[NSString stringWithFormat:@"%zd/%zd",Page,num1];
            
        }
            break;
        case 101:
        {
            if (Page >= num1) {
                [_tableView.footer endRefreshing];
                return;
            }
            if(Page >= num1 - 1){
                right.enabled=NO;
                left.enabled = YES;
                
            } else {
                right.enabled = YES;
                left.enabled = YES;
            }
            

            
            Page= Page+1;
           [self doneLoadMoreMessage:101];
            [_tableView.footer endRefreshing];
            lable.text=[NSString stringWithFormat:@"%zd/%zd",Page,num1];
            if (Page>1) {
            
            }
           
        }
            break;
        case 102:
        {
            
        }
            break;
        default:
            break;
    }
    
}

- (void)deleRecrod
{
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"确定删除所有的聊天记录?"];
    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
        
        if (self.group) {
            
            [self.messageMgr delGroupMessageWithGroupId:self.group.GroupId];
        } else {
            [self.messageMgr delMessageWithMineUserId:self.currentUser.UserID FriendUserId:self.member.UserID];
        }
        
        [self.messages removeAllObjects];
        [self.tableView reloadData];
        
        lable.text=[NSString stringWithFormat:@"0/0"];
        
        Page = 0;
        num1 = 0;
        right.enabled = NO;
        left.enabled = NO;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DELRECORD" object:nil];
    }];
    
    [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
        
        
    }];
    [alert show];

}

- (void)setBackgroundColor:(UIColor *)color
{
    self.view.backgroundColor = color;
    self.tableView.backgroundColor = color;
    self.tableView.separatorColor = color;
}


- (void)back
{
    [[CHSAudioPlayer sharedInstance] stopSound];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated
{
    //    [self scrollToBottomAnimated:NO];
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
    [self scrollToBottomAnimated:YES];
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_6_1
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
#else
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
#endif
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self setEditing:NO animated:YES];

    //bug6095 fixed by 荣则兵
    //    [_chatToolBar.contentText setText:@""];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:ChatToolBarMoved object:nil];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:SendChatMessage object:nil];
    
//    NSLog(@"*** %@: didReceiveMemoryWarning ***", self.class);
}

#pragma mark - View rotation
//- (BOOL)shouldAutorotate
//{
//    return NO;
//}
//
//- (NSUInteger)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
//{
//    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
//    [self.tableView reloadData];
//    [self.tableView setNeedsLayout];
//}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        
        return self.messages.count;
    } else {
        return self.searchArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        
        if(section == 0)return 5.0f;
        return 0.01f;
    } else{
        return 0.01f;
    }
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (_tableView == tableView) {
        if(section == 0){
            UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH,0)];
            view.backgroundColor =[UIColor clearColor];
            return view;
            
        }
        return nil;
  
    } else {
        return nil;
    }
    
}
-(void)openredPacketWithIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_tableView == tableView) {
        CHBubbleMessageType type = [self.delegate messageTypeForRowAtIndexPath:indexPath];
        CHBubbleStyle bubbleStyle = [self.delegate messageStyleForRowAtIndexPath:indexPath];
        CHAvatarStyle avatarStyle = [self.delegate avatarStyle];
        BOOL ismap = [self.delegate ismapForRowAtIndexPath:indexPath];
        ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
        BOOL hasTimestamp = [self shouldHaveTimestampForRowAtIndexPath:indexPath];
        BOOL hasSendeName = NO;
        if (M_ISSTRNULL(msg.fromName)) {
            hasSendeName = NO;
        } else {
            hasSendeName = YES;
        }
        BOOL isNotice = [self.dataSource isNoticeForRowAtIndexPath:indexPath];
        NSString *CellID = [NSString stringWithFormat:@"MessageCell_%d_%d_%d_%d", type, bubbleStyle, hasTimestamp,isNotice];
        
        CHBubbleMessageCell *cell = (CHBubbleMessageCell *)[tableView dequeueReusableCellWithIdentifier:CellID];
        
        if(!cell)
        {
            cell = [[CHBubbleMessageCell alloc] initWithBubbleType:type
                                                       bubbleStyle:bubbleStyle
                                                       avatarStyle:avatarStyle
                                                      hasTimestamp:hasTimestamp
                                                          isNotice:isNotice isHasSenderName:hasSendeName
                                                   reuseIdentifier:CellID ismap:ismap];
            [cell setBackgroundColor:tableView.backgroundColor];
            //        [cell.avatarView addTarget:self action:@selector(jumpToDetailInfoView:) forControlEvents:UIControlEventTouchUpInside];
        }
        cell.cellIndexPath = indexPath;
        cell.chidMessage = msg;
        cell.delegate = self;
        cell.messageList = self.messages;
        [cell setMemoryID:[self.dataSource memoryIDForRowAtIndexPath:indexPath]];
        if(hasTimestamp)
        {
            [cell setTimestamp:[self.dataSource timestampForRowAtIndexPath:indexPath]];
        }
        
        switch (type) {
            case CHBubbleMessageTypeReceived:
                [cell setAvatarImage:[self.dataSource avatarImageURIForReceivedMessageRowAtIndexPath:indexPath]];
                break;
                
            case CHBubbleMessageTypeSended:
                [cell setAvatarImage:[self.dataSource avatarImageURIForSendedMessageRowAtIndexPath:indexPath]];
                break;
        }
        
        [cell setName:[self.dataSource senderNameForRowAtIndexPath:indexPath]];
        [cell setTitle:[self.dataSource senderTitleForRowAtIndexPath:indexPath]];
        switch (bubbleStyle) {
            case CHBubbleStyleText:
            {
                [cell setMessage:[self.dataSource textForRowAtIndexPath:indexPath] withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
                break;
            }
            case CHBubbleStyleVoice:
            {
                [cell setIndexPathForVoice];
                [cell setVoice:[self.dataSource voiceURIForRowAtIndexPath:indexPath]
                     totalTime:[self.dataSource voiceTimeForRowAtIndexPath:indexPath]
                        isRead:msg.isPlayed
                    withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                      fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                        fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                      chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
                break;
            }
            case CHBubbleStylePicture:
            {
                NSArray *tmpArray = [self.dataSource pictureURIArrayForRowAtIndexPath:indexPath];
                NSInteger acount = [tmpArray count];
                if (acount >= 2) {
                    [cell setPicture:[tmpArray objectAtIndex:0]
                             nextURI:[tmpArray objectAtIndex:1]
                          withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                            fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                              fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                            chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
                }
                else
                {
                    [cell setPicture:nil nextURI:nil withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                            fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                              fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                            chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
                }
                break;
            }
            case CHBubbleStyleFile:
            {
                [cell setFileWithStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                               fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                                 fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                               chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
            }
                break;
            case CHBubbleStyleRedPacket:
            {
                ChildHoodMessage *message = self.messages[indexPath.row];
                [cell setRedPacketInfo:message.messageContent withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
            }
                break;
            case CHBubbleStyleVideo:
            {
                [cell setVideo:nil withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath] fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath] chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] chileMessage:self.messages[indexPath.row]];
                break;
            }
                

            case CHBubbleStyleEmoticon:
            {
                break;
            }
            case CHBubbleStyleShke:
            {
                [cell setMessage:[self.dataSource textForRowAtIndexPath:indexPath] withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
                break;
                
            }
            default:
                break;
        }
        [cell setMessageStatus:msg.messageStatus];
        return cell;
 
    } else {
        id obj = self.searchArray[indexPath.row];
        if ([obj isKindOfClass:[CMessageFrame class]]) {
            CMessageFrame *messageFrame = (CMessageFrame *)obj;
            CCHatRecordCell *cell = [CCHatRecordCell chatRecordCellWithTableView:tableView];
//            cell.messageFrame = messageFrame;
            //bug 8514 fixed by lixu
            [cell setCMessageFrame:messageFrame withSearchText:_searchBar.text];
            return cell;
        } else {
            NSString *title =  (NSString *)obj;
            static NSString *SettingCellIdentifier = @"SettingTextCell";
            SettingTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:SettingCellIdentifier];
            if (textCell == nil) {
                textCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingTextCell" owner:self options:nil] objectAtIndex:0];
            }
            textCell.titleLabel.text = [NSString stringWithFormat:@"搜索“%@”",title];
            return textCell;
        }
    }
}


#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == tableView) {
        CHBubbleStyle bubbleStyle = [self.delegate messageStyleForRowAtIndexPath:indexPath];
        ChildHoodMessage *message = [self.messages objectAtIndex:indexPath.row];
        MessageSendType type  = message.messageStatus;
        CGFloat cellheight = 0;
        if (type == kMessageUserMute) {
            cellheight = SendAlert_Label_Height;
        }
        BOOL flag = [self shouldHaveTimestampForRowAtIndexPath:indexPath];
        
        BOOL hasSendeName = NO;
        if (M_ISSTRNULL(message.fromName)) {
            hasSendeName = NO;
        } else {
            hasSendeName = YES;
        }
        if (bubbleStyle == CHBubbleStylePicture || bubbleStyle == CHBubbleStyleFile)
        {
            CGFloat timestampHeight = flag ? (TIMESTAMP_LABEL_HEIGHT + 2*INSET_HEIGHT) : 0.0f;
            CGFloat hasSenderNameHeight = hasSendeName ? SENDERNAME_LABEL_HEIGHT : 0.0f;
            cellheight += timestampHeight + hasSenderNameHeight + INSET_HEIGHT + kCHAvatarSize + INSET_HEIGHT + SENDERNAME_LABEL_HEIGHT + SENDERTITLE_LABEL_HEIGHT + INSET_HEIGHT;
            cellheight += 60;
        }
        else if (bubbleStyle == CHBubbleStyleVideo)
        {
            CGFloat timestampHeight = flag ? (TIMESTAMP_LABEL_HEIGHT + 2*INSET_HEIGHT) : 0.0f;
            CGFloat hasSenderNameHeight = hasSendeName ? SENDERNAME_LABEL_HEIGHT : 0.0f;
            cellheight += timestampHeight + hasSenderNameHeight + INSET_HEIGHT + kCHAvatarSize + INSET_HEIGHT + SENDERNAME_LABEL_HEIGHT + SENDERTITLE_LABEL_HEIGHT + INSET_HEIGHT;
            cellheight += 100;
        }

        else
        {
            cellheight +=[CHBubbleMessageCell neededHeightForText:[self.dataSource textForRowAtIndexPath:indexPath]
                                                        timestamp:flag isHasSenderName:hasSendeName];
        }
        return cellheight;
    }
    else {
      
        id obj = self.searchArray[indexPath.row];
        if ([obj isKindOfClass:[CMessageFrame class]]) {
            CMessageFrame *message = (CMessageFrame *)obj;
            return message.cellHeight;
            
        } else {
            return 50.0f;
        }
      
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == tableView) {
        return;
    } else {
        
        id obj = self.searchArray[indexPath.row];
        if ([obj isKindOfClass:[CMessageFrame class]]) {
            CMessageFrame *messageFrame = (CMessageFrame *)obj;
            IMSearchChatRecordController *search = [[IMSearchChatRecordController alloc] init];
        
            CMessageModel *mo = [self.messageMgr loadMessageWithMessageId:messageFrame.message.messageId];
            search.message = mo;
            if (self.group) {
                search.group = self.group;
                search.member = nil;
            } else {
                search.member = self.member;
                search.group = nil;
            }
            [self.navigationController pushViewController:search animated:YES];
        } else {
            NSString *title = (NSString *)obj;
            _searchBar.text = title;
            [_searchBar resignFirstResponder];
            NSArray *array = nil;
            if (self.group) {
                
                array = [self.messageMgr searchMessageWithSearchStr:title groupId:self.group.GroupId];
            } else {
                array = [self.messageMgr searchMessageWithSearchStr:title mineId:self.currentUser.UserID friendId:self.member.UserID];
            }
            
            [self handleMessageData:array];
            if (self.searchArray.count>0) {
                WZSearchMessageResultController *search = [[WZSearchMessageResultController alloc]initWithSearchText:title];
                search.messageArray = self.searchArray;
                search.isChatRecord = YES;
                [self.navigationController pushViewController:search animated:YES];

            }
            else
            {
                [_searchDisplayController.searchResultsTableView reloadData];

            }
        }
    }
    
}
#pragma mark - Messages view controller
- (BOOL)shouldHaveTimestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch ([self.delegate timestampPolicy]) {
        case CHMessagesViewTimestampPolicyAll:
            return YES;
            
        case CHMessagesViewTimestampPolicyAlternating:
            return indexPath.row % 2 == 0;
            
        case CHMessagesViewTimestampPolicyEveryThree:
            return indexPath.row % 3 == 0;
            
        case CHMessagesViewTimestampPolicyEveryFive:
            return indexPath.row % 5 == 0;
            
        case CHMessagesViewTimestampPolicyCustom:
            if([self.delegate respondsToSelector:@selector(hasTimestampForRowAtIndexPath:)])
                return [self.delegate hasTimestampForRowAtIndexPath:indexPath];
            
        default:
            return NO;
    }
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    
    if(rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:animated];
    }
}

#pragma mark --ChatMoreViewDelegate--
- (void)sendFileWithArray:(NSArray *)array
{
    
}





//- (void)jumpToDetailInfoViewWithIndexPath:(NSIndexPath *)indexPath
//{
//    ChildHoodMessage *chmessage = self.messages[indexPath.row];
//    CContactModel *model;
//    if (chmessage.isMine == CHBubbleMessageTypeSended) {
//        MyInformationVC *info = [[MyInformationVC alloc] init];
//        [self.navigationController pushViewController:info animated:YES];
//        
//    } else {
//        model = [[[CContactMgr alloc] init] loadContactWithUserId:chmessage.MineUserId];
//        GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
//        vc.member = model;
//        vc.isFromChat = NO;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//
//}

- (void)jumptoDownLoadFileWithIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    IMFileDownLoadController *down = [[IMFileDownLoadController alloc] init];
    down.chMessage = chMessage;
    [self.navigationController pushViewController:down animated:YES];
}
-(void)jumptoMapWithIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    ShowMapViewController *map = [[ShowMapViewController alloc]init];
    NSArray *array = [chMessage.fileName componentsSeparatedByString:@","];
    map.location = [[CLLocation alloc]initWithLatitude: [array[1] doubleValue] longitude: [array[2] doubleValue]];
    [self.navigationController pushViewController:map animated:YES];
}

//- (void)ShowGroupDetail
//{
//    GroupDetailVC *vc = [[GroupDetailVC alloc] init];
//    vc.group = self.group;
//    [self.navigationController pushViewController:vc animated:YES];
//}
//
//- (void)showContactDetail
//{
//    GroupMemberDetailVC *vc = [[GroupMemberDetailVC alloc] init];
//    vc.member = self.member;
//    vc.isFromChat = YES;
//    vc.isFromGroupChat = NO;
//    [self.navigationController pushViewController:vc animated:YES];
//    
//}
#pragma mark - View lifecycle


-(void)updateMemory:(NSNotification *)noti
{
    
    
}

- (void)loadMessage
{
    NSArray *array;
    NSInteger perPage;
    if (num2 == 0) {
        perPage = 10;
    } else {
        // bug 8532 fixed by lixu
        perPage = 10 + num2;
    }
    if (self.member) {
        array = [self.messageMgr loadMessageWithMineId:self.currentUser.UserID FrinendId:self.member.UserID Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage]];
        
    } else if (self.group) {
        array = [self.messageMgr loadGroupMessageWithGroupId:self.group.GroupId Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage]];
    }
   first = array.lastObject;
   last = array.firstObject;
    self.minMessage = first;
    self.maxMessage = last;
    //    [self.messages addObjectsFromArray:_resultControl.fetchedObjects];
    
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
        
        [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
    }];
    
    if (self.messages.count > 0) {
        [self.tableView reloadData];
        //            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0];
        //            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        [self scrollToBottomAnimated:YES];
    }
    
}

- (void)doneLoadMoreMessage:(NSInteger)leftnum
{
   
    //    _reloading = NO;
    [self.messages removeAllObjects];
    NSArray *array;
     // bug 8532 fixed by lixu
    NSInteger perPage = 10;
    if (leftnum == 100) {
        if (self.group) {
          array = [self.messageMgr loadMoreGroupHistoryMessageWithGroupId:self.group.GroupId Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage] TimeStamp:self.minMessage.TimeStamp];
        } else {
            array = [self.messageMgr loadMoreHistoryMessageWithFriendId:self.member.UserID mineId:self.currentUser.UserID Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage] TimeStamp:self.minMessage.TimeStamp];
        }
        
            last = array.firstObject;
            self.maxMessage = last;
            
            first = array.lastObject;
            self.minMessage = first;
        
            
            //    CMessageModel *last = array.lastObject;
            //    self.minMessageIndex = last.MessageIndex;
            //    self.maxMessageIndex = first.MessageIndex;
            
            
            
            [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
                
                [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
            }];
            
            [self.tableView reloadData];
        if (self.messages.count > 0) {
            
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
        
        
            
            }else{
                if (Page == num1) {
                    perPage += num2;
                }
                if (self.group) {
                  array = [self.messageMgr loadreduceMoreGroupHistoryMessageWithGroupId:self.group.GroupId Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage] TimeStamp:self.maxMessage.TimeStamp];
                } else {
                    array = [self.messageMgr loadreduceMoreGroupHistoryMessageWithFriendId:self.member.UserID mineId:self.currentUser.UserID Page:@"0" PerPage:[NSString stringWithFormat:@"%zd",perPage] TimeStamp:self.maxMessage.TimeStamp];
                }
            
            last = array.lastObject;
            first = array.firstObject;
            self.maxMessage = last;
            
            self.minMessage = first;
             [array enumerateObjectsUsingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
                 [self.messages addObject:[self handleChildHoodMessageWithMessage:obj]];
                 
             }];
                [self.tableView reloadData];
                if (self.messages.count > 0) {
                    
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                }
                
   
        }
    
}

- (ChildHoodMessage *)handleChildHoodMessageWithMessage:(CMessageModel *)obj
{
    SNSPMessage* snspMessage  = nil;
    //        NSString* strFile = [NSString stringWithFormat:@"message_%lld.data", messageModel.messageIndex];
    //        snspMessage = [CHMessageManager loadSNSPMessage:strFile];
    if(snspMessage == nil)
    {
        
        SNSPMessage_Builder* messageBuilder = [[SNSPMessage builder] clear];
        
        
        
        [messageBuilder setContent:[obj.MessageContent dataUsingEncoding:NSUTF8StringEncoding]];
        //            [messageBuilder setMemoryId:[messageModel.memoryId intValue]];
        //            [messageBuilder setRoomId:[messageModel.roomId longLongValue]];
        //            [messageBuilder setRelativeType:[messageModel.relativeType intValue]];
        if (self.group) {
            if (obj.isMineSend == YES) {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupUploadImagePathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName]];
            } else {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupDownloadImagePathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName]];
            }
            
        } else {
            
            if (obj.isMineSend == YES) {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] personalUploadImagePathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:obj.FileName]];
            } else {
                [messageBuilder addAttachmentFileKeys:[[[ChildHoodService defaultService] groupDownloadImagePathWithGroupId:self.member.UserID] stringByAppendingPathComponent:obj.FileName]];
            }
        }
        
        int64_t tt = obj.TimeStamp.longLongValue;//[[UIUtil antiGetSystemTime:messageModel.messageTime] timeIntervalSince1970]*1000;
        [messageBuilder setCreateTime:tt];
        if ([obj.MessageType isEqualToString:@"text"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKMessage];
        } else if ([obj.MessageType isEqualToString:@"voice"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKAudio];
        } else if ([obj.MessageType isEqualToString:@"image"]) {
            [messageBuilder setMaterialType:SNSPMaterialTypeKImage];
        } else if ([obj.MessageType isEqual:@"file"]){
            [messageBuilder setMaterialType:SNSPMaterialTypeKFile];
        } else if ([obj.MessageType isEqual:@"shke"]){
             [messageBuilder setMaterialType:SNSPShake];
        } else if ([obj.MessageType isEqual:@"video"]){
            [messageBuilder setMaterialType:SNSPMaterialTypeKVideo];
        } else if ([obj.MessageType isEqualToString:@"redpacket"]){
            [messageBuilder setMaterialType:SNSRedPacket];
        }

        
        [messageBuilder setMessageType:SNSPMessageTypeKMessageType];
        [messageBuilder setMessageId:2222222];
        snspMessage = [messageBuilder build];
        
    }
    ChildHoodMessage* chmessage = [[ChildHoodMessage alloc]initWithSNSMessage:snspMessage];
    chmessage.messageStatus = obj.MessageSendedStatus;
    chmessage.SoundLenth = obj.MessageContent.integerValue;
    chmessage.messageDBID = obj.MessageIndex;
    chmessage.isPlayed = obj.SoundPlayStatus;
    chmessage.fileName = obj.FileName;
    chmessage.messageId = obj.MessageId;
    
    if (self.group) {
        if (obj.isMineSend) {
            
        } else {
            chmessage.fromName = [self.conMgr loadContactNameWithUserId:obj.MineUserId];
        }
    }

    //        chmessage.totalCount = messageModel.totalCount;
    //
    //        chmessage.messageDBID = messageModel.messageIndex;
    if ([obj.MessageType isEqualToString:@"text"]) {
    } else if ([obj.MessageType isEqualToString:@"voice"]) {
        if (self.group) {
            if (obj.isMineSend) {
                chmessage.fileUri = [[[ChildHoodService defaultService] groupUploadSoundPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName];
                
            } else {
                chmessage.fileUri = [[[ChildHoodService defaultService] groupDownloadSoundPathWithGroupId:self.group.GroupId] stringByAppendingPathComponent:obj.FileName];
            }
        } else {
            if (obj.isMineSend) {
                chmessage.fileUri = [[[ChildHoodService defaultService] personalUploadSoundPathWithUserId:self.currentUser.UserID] stringByAppendingPathComponent:obj.FileName];
                
            } else {
                chmessage.fileUri = [[[ChildHoodService defaultService] personalDownloadSoundPathWithUserId:self.member.UserID] stringByAppendingPathComponent:obj.FileName];
            }

        }
    } else if ([obj.MessageType isEqualToString:@"image"]||[obj.MessageType isEqualToString:@"video"]) {
        chmessage.fileUri = obj.Stream;
    }
    
    if (obj.isMineSend) {
        chmessage.isMine = CHBubbleMessageTypeSended;
        //            chmessage.fileUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.currentUser.UserID];
    } else {
        chmessage.isMine = CHBubbleMessageTypeReceived;
        
    }
    chmessage.GroupId = obj.GroupId;
    chmessage.MineUserId = obj.MineUserId;
    chmessage.FriendUserId = obj.FriendUserId;
    if ([self.conMgr isKefuContactWithUserId:obj.FriendUserId]) {
        chmessage.isKefu = YES;
    } else {
        chmessage.isKefu = NO;
    }

    chmessage.fileLenth = obj.FileSize;
    //        chmessage.messageFilePath = messageModel.messageFilePath;
    
    //        chmessage.materialCount = materialCount;
    
    //        chmessage.isRead = [messageModel.isRead boolValue];;
    
    //        chmessage.isShowing = [messageModel.isShowing boolValue];;
    
    //        chmessage.isPlayed = [messageModel.isPlayed boolValue];
    
    //        chmessage.isDownloaded = [messageModel.isDownloaded boolValue];
    return chmessage;
}


#pragma mark chbubumessagecellDelegate
-(BOOL)ismapForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if ([msg.fileName hasPrefix:@"location"]) {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (CHBubbleMessageType)messageTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    
    //    return (msg.memoryID == _myChildHood.memoryId && msg.relativeType == _myRelativeType) ? CHBubbleMessageTypeSended : CHBubbleMessageTypeReceived;
    return msg.isMine;
}
- (CHBubbleStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = nil;
    if(indexPath.row < [self.messages count])
    {
        msg = [self.messages objectAtIndex:indexPath.row];
    }
    CHBubbleStyle style;
    switch (msg.messageType) {
        case SNSPMaterialTypeKMessage:
        {
            //NSLog(@"文字类型");
            style = CHBubbleStyleText;
            break;
        }
        case SNSPMaterialTypeKAudio:
        {
            //NSLog(@"音频类型");
            style = CHBubbleStyleVoice;
            break;
        }
        case SNSPMaterialTypeKEmotion:
        {
            //NSLog(@"表情类型");
            style = CHBubbleStyleEmoticon;
            break;
        }
        case SNSPMaterialTypeKImage:
        {
            //NSLog(@"图片类型");
            style = CHBubbleStylePicture;
            break;
        }
        case SNSPMaterialTypeKFile:
        {
            style = CHBubbleStyleFile;
            break;
        }
        case SNSPMaterialTypeKVideo:
        {
            style = CHBubbleStyleVideo;
            break;
        }
        case SNSPShake:
        {
            style = CHBubbleStyleShke;
            break;
        }
        case SNSRedPacket:
        {
            style = CHBubbleStyleRedPacket;
            break;
        }
        default:
            //NSLog(@"未知类型");
            break;
    }
    return style;
}

- (CHMessagesViewTimestampPolicy)timestampPolicy
{
    return CHMessagesViewTimestampPolicyCustom;
}

- (CHAvatarStyle)avatarStyle
{
    return CHAvatarStyleSquare;
}

- (BOOL)hasTimestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row>= [self.messages count])
    {
        return NO;
    }
    ChildHoodMessage *curMsg = [self.messages objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        return YES;
    }
    else
    {
        ChildHoodMessage *preMsg = [self.messages objectAtIndex:indexPath.row-1];
        int64_t curMsgTime = [curMsg getMessageGMTTime]/1000/60/5;
        int64_t preMsgTime = [preMsg getMessageGMTTime]/1000/60/5;
        
        if (curMsgTime == preMsgTime) {
            return NO;
        }
    }
    return YES;
}
//bug 8521 fixed by lixu
-(void)menuControllerDidForWardWithString:(NSString *)str
{
    [ChildHoodService defaultService].forwardText = str;
    [ChildHoodService defaultService].imgLocalFilePath = nil;
    [ChildHoodService defaultService].fileModel = nil;
    IMFowardController *foward = [[IMFowardController alloc] init];
    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:foward];
    [self presentViewController:nav animated:YES completion:nil];

}
#pragma mark - Messages view data source
- (int64_t)voiceMessageDBIDForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.messageDBID;
}

- (BOOL)voiceIsPlayForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.isPlayed;
}

-(CGFloat)voiceTimeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.SoundLenth;
}

- (NSArray *)pictureURIArrayForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    NSString* str = msg.fileUri;
    if(str.length < 3)str = msg.nextFileUri;
    if(str.length < 3)str = nil;
    NSString* str2 = msg.nextFileUri;
    if(str2.length <3) str2 = nil;
    return [NSArray arrayWithObjects:str,str2, nil];
}

- (NSString *)fileNameForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.fileName;
    
}
- (NSString *)fileIdForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if (self.group) {
        return msg.GroupId;
    } else {
        if (msg.isMine == CHBubbleMessageTypeSended) {
            return msg.MineUserId;
        } else {
            return msg.FriendUserId;
        }
    }
    
}

- (NSString *)chatTypeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.group) {
        return @"groupChat";
    } else {
        return @"chat";
    }
}
- (NSString *)voiceURIForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.fileUri;
}

- (NSString *)senderNameForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.fromName;
}

- (NSString *)senderTitleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    return msg.title;
}

- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.messageContent;
}

- (NSDate *)timestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //NSLog(@"%@",[msg getMessageTime]);
    return [msg getMessageTime];
}

- (NSString *)avatarImageURIForReceivedMessageRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //    return msg.senderPortraitImageUri;
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    if (self.group) {
        return [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.MineUserId];
    } else {
        return [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.FriendUserId];
    }
    
}

- (NSString *)avatarImageURIForSendedMessageRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSString *uri = [[ChildHoodService defaultService].childHoodMemory getProfilePictureUri];
    //    return uri;
    ChildHoodMessage *chMessage = self.messages[indexPath.row];
    return  [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:chMessage.MineUserId];
}

- (int32_t)messageStatusForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    
    return msg.messageStatus;
}

- (uint32_t)memoryIDForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    return msg.memoryID;
}

- (BOOL)isNoticeForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    if (msg.type == SNSPMessageTypeKNoticeType) {
        return YES;
    }
    return NO;
}


- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


-(void)handleMessageData:(NSArray*)messages
{
    [self.searchArray removeAllObjects];
    [messages enumerateObjectsUsingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
        
        ChatMessageListCellData *data = [[ChatMessageListCellData alloc] init];
        data.messageIndex = obj.MessageIndex;
        if (obj.GroupId.length > 3) {
            data.FriendUserId = obj.MineUserId;
            data.senderName = obj.MineUserName;
            data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.MineUserId];
            
        } else {
            if (obj.isMineSend) {
                data.senderName = obj.MineUserName;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.MineUserId];
            } else {
                data.senderName = obj.FriendUserName;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.FriendUserId];
            }
        }
        data.content = obj.MessageContent;
        data.MineUserId = obj.MineUserId;
        data.FriendJid = obj.FriendJid;
        data.MineJid = obj.MineJid;
        data.GroupId = obj.GroupId;
        data.isRead = obj.ReadStatus;
        data.messageId = obj.MessageId;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:obj.TimeStamp.longLongValue / 1000.0];
        data.sendTime = [UIUtil timeForMessageListStyle:date];

        CMessageFrame *messageFrame = [[CMessageFrame alloc] init];
        messageFrame.message = data;
        [self.searchArray addObject:messageFrame];
    }];
    //        CContactModel *contact = [[[CContactMgr alloc] init] loadContactWithUserId:obj.FriendUserId];
    
}

#pragma mark searchBar 代理方法

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSArray *array = nil;
    if (self.group) {
        
       array = [self.messageMgr searchMessageWithSearchStr:searchBar.text groupId:self.group.GroupId];
    } else {
        array = [self.messageMgr searchMessageWithSearchStr:searchBar.text mineId:self.currentUser.UserID friendId:self.member.UserID];
    }
    
    [self handleMessageData:array];
    if (self.searchArray.count>0) {
        WZSearchMessageResultController *search = [[WZSearchMessageResultController alloc]initWithSearchText:searchBar.text];
        search.messageArray = self.searchArray;
        search.isChatRecord = YES;
        [self.navigationController pushViewController:search animated:YES];
        
    }
    else
    {
    [_searchDisplayController.searchResultsTableView reloadData];
    }
}
//bug 8510 fixed by lixu
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0){
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{ for(UIView *subview in controller.searchResultsTableView.subviews) {
    
    if([subview isKindOfClass:[UILabel class]]) {
        
        [(UILabel*)subview setText:@"未找到匹配的信息"];
    }
    
}
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.searchArray removeAllObjects];
    [self.searchArray addObject:searchText];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                     // called when text starts editing
{
    searchBar.showsCancelButton = YES;
    for(id cc in [_searchDisplayController.searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}



#pragma mark -

@end
